package com.example.bicycle.service.impl;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.bicycle.domain.entity.User;
import com.example.bicycle.domain.vo.UserVo;
import com.example.bicycle.service.LoginService;
import com.example.bicycle.service.UserService;
import com.example.bicycle.utils.BeanCopyUtils;
import com.example.bicycle.utils.RedisCache;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service("loginService")
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private UserService userService;
    @Override
    public SaResult login(User user) {
        /* 判断是否有空，有空登录不成功 */
        if(StringUtils.hasText(user.getUsername())&&StringUtils.hasText(user.getPassword())) {
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("username",user.getUsername());
            queryWrapper.eq("password",user.getPassword());
            User res = userService.getOne(queryWrapper);
            if(res != null) {
                //登录上
                StpUtil.login(res.getUserId());
                //获取 Token 相关参数
                SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
                //封装成UserVo（不返回密码）
                UserVo userVo = BeanCopyUtils.copyBean(res, UserVo.class);
                userVo.setSaTokenInfo(tokenInfo);
                //返回前端
                return SaResult.get(200,"登录成功",userVo);
            }
            return SaResult.error("登录失败");
        }
        return SaResult.error("用户名或密码不能为空");
    }


    public SaResult logout() {
        StpUtil.logout();
        return SaResult.ok();
    }
}
